package com.innerchic.weqiuqiu.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.innerchic.annotations.base.ActivitySetting;
import com.innerchic.annotations.base.BindActivityLayoutHolder;
import com.innerchic.huhu.http.HttpRequest;
import com.innerchic.mapper.app.SuperActivity;
import com.innerchic.mapper.log.Logger;
import com.innerchic.mapper.tool.SystemTool;
import com.innerchic.mapper.tpool.ThreadFactory;
import com.innerchic.mapper.tpool.ThreadPoolNorm;
import com.innerchic.mapper.tpool.ThreadProxy;
import com.innerchic.weqiuqiu.R;
import com.innerchic.weqiuqiu.utils.NotificationUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：wedudu
 * 日    期：2022/1/13 16:08
 * 包    名：com.innerchic.weqiuqiu.ui
 * 描    述：检查权限
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */

@BindActivityLayoutHolder
@ActivitySetting(layout = "activity_check_permission", modificationActionBar = false, textTheme = true, swipe = true)
public class CheckPermissionsActivity extends SuperActivity {

    private static final int INSTALL_APK_REQUESTCODE = 1000;

    private CheckPermissionsActivityLayoutHolder holder;

    private boolean isSelfClick = false;

    @Override
    public void create() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setTitle(Html.fromHtml("<font color='#000'>检查权限</font>"));
        }
        //设置监听
        holder.hasAndroidAuto.setOnClickListener(v -> {
            isSelfClick = false;
            if (isHasAndroidAuto(this)) {
                showToast("AndroidAuto已安装");
                return;
            }
            loadAndroidAuto();
        });
        holder.xuanfuchuangSetting.setOnClickListener(v -> {
            isSelfClick = false;
            showSuspensionWindow(this);
        });
        holder.tongzhiSetting.setOnClickListener(v -> {
            isSelfClick = false;
            NotificationUtils.gotoNotificationAccessSetting(this);
        });
        holder.houtaiyunxingSetting.setOnClickListener(v -> {
            isSelfClick = false;
            requestIgnoreBatteryOptimizations(this);
        });
        holder.ziqidongSetting.setOnClickListener(v -> {
            isSelfClick = true;
            selfStartManagerSettingIntent(this);
        });
    }

    private boolean isLoadAutoing = false;

    private void loadAndroidAuto() {
        if (isLoadAutoing) {
            return;
        }
        isLoadAutoing = true;
        ThreadFactory.getInstance().execute(() -> {
            String path = getFilesDir().getPath();
            path = path + "/android_auto.apk";
            Logger.d("Path:" + path);
            //文件存在
            File file = new File(path);
            if (file.exists()) {
                attemptInstallApk(file);
                isLoadAutoing = false;
                return;
            }
            //复制文件
            try {
                InputStream is = getAssets().open("android_auto_simple.apk");
                FileOutputStream fos = new FileOutputStream(new File(path));
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();

                //尝试安装
                attemptInstallApk(file);
            } catch (IOException e) {
                e.printStackTrace();
                //文件复制失败
                getMainHandler().post(() -> showToast("安装失败,请自行下载安装AndroidAuto或者安装一个包名为'com.google.android.projection.gearhead'的App"));
                SystemTool.copyClipboard(CheckPermissionsActivity.this, "com.google.android.projection.gearhead");
            }
            isLoadAutoing = false;
        });
    }

    private void attemptInstallApk(File file) {
        getMainHandler().post(() -> {
            //检查权限
            boolean canRequestPackageInstalls = true;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O
            ) {
                canRequestPackageInstalls = CheckPermissionsActivity.this.getPackageManager().canRequestPackageInstalls();
            }
            Logger.d("canRequestPackageInstalls:" + canRequestPackageInstalls);
            if (!canRequestPackageInstalls) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},
                        INSTALL_APK_REQUESTCODE);
            } else {
                installApk(file.getPath());
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == INSTALL_APK_REQUESTCODE && grantResults[0] == 0) {
            String path = getFilesDir().getPath();
            path = path + "/android_auto.apk";
            installApk(path);
        } else {
            showToast("请前往'设置->允许安装未知应用'中设置允许后安装.");
            Logger.d("GrantResults:" + grantResults[0]);
        }
    }

    /**
     * 安装插件
     */
    private void installApk(String finalPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(finalPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(this, "com.innerchic.weqiuqiu.fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initState();

        if (isSelfClick) {
            //应用自启
            new AlertDialog.Builder(this)
                    .setTitle("自启动权限")
                    .setMessage(Html.fromHtml("是否已经开启了\"<font color='red'>自启动</font>\"权限"))
                    .setNegativeButton(Html.fromHtml("<font color='#000000'>已开启</font>"), (dialog, which) -> {
                        boolean commit = getSharedPreferences("permissions_status", 0).edit().putBoolean("selfStarting", true).commit();
                        initState();
                    })
                    .setNeutralButton(Html.fromHtml("<font color='#000000'>未开启</font>"), (dialog, which) -> {
                        boolean commit = getSharedPreferences("permissions_status", 0).edit().putBoolean("selfStarting", false).commit();
                        initState();
                    }).show();
        }
    }

    /**
     * 初始化状态
     */
    private void initState() {
        //初始化状态
        if (isHasAndroidAuto(this)) {
            //已持有
            holder.installAndroidAuto.setText("已安装");
            holder.installAndroidAuto.setBackgroundResource(R.drawable.button_quanxian_enable);
            holder.installAndroidAuto.setTextColor(getResources().getColor(R.color.text_gray));
        } else {
            //未持有
            holder.installAndroidAuto.setText("去安装");
            holder.installAndroidAuto.setBackgroundResource(R.drawable.button_quanxian);
            holder.installAndroidAuto.setTextColor(getResources().getColor(R.color.white));
        }
        if (CheckPermissionsActivity.isNotHaveSuspensionWindow(this)) {
            //未持有
            holder.openXuanfuchuang.setText("去开启");
            holder.openXuanfuchuang.setBackgroundResource(R.drawable.button_quanxian);
            holder.openXuanfuchuang.setTextColor(getResources().getColor(R.color.white));
        } else {
            //已持有
            holder.openXuanfuchuang.setText("已开启");
            holder.openXuanfuchuang.setBackgroundResource(R.drawable.button_quanxian_enable);
            holder.openXuanfuchuang.setTextColor(getResources().getColor(R.color.text_gray));
        }
        boolean listenersEnabled = NotificationUtils.isNotificationListenersEnabled(this);
        if (listenersEnabled) {
            //已持有
            holder.openTongzhi.setText("已开启");
            holder.openTongzhi.setBackgroundResource(R.drawable.button_quanxian_enable);
            holder.openTongzhi.setTextColor(getResources().getColor(R.color.text_gray));
        } else {
            //未持有
            holder.openTongzhi.setText("去开启");
            holder.openTongzhi.setBackgroundResource(R.drawable.button_quanxian);
            holder.openTongzhi.setTextColor(getResources().getColor(R.color.white));
        }
        if (CheckPermissionsActivity.isIgnoringBatteryOptimizations(this)) {
            //已持有
            holder.openHoutaiyunxing.setText("已开启");
            holder.openHoutaiyunxing.setBackgroundResource(R.drawable.button_quanxian_enable);
            holder.openHoutaiyunxing.setTextColor(getResources().getColor(R.color.text_gray));
        } else {
            //未持有
            holder.openHoutaiyunxing.setText("去开启");
            holder.openHoutaiyunxing.setBackgroundResource(R.drawable.button_quanxian);
            holder.openHoutaiyunxing.setTextColor(getResources().getColor(R.color.white));
        }
        if (CheckPermissionsActivity.isHaveSelfStarting(this)) {
            //已持有
            holder.openZiqidong.setText("已开启");
            holder.openZiqidong.setBackgroundResource(R.drawable.button_quanxian_enable);
            holder.openZiqidong.setTextColor(getResources().getColor(R.color.text_gray));
        } else {
            //未持有
            holder.openZiqidong.setText("去开启");
            holder.openZiqidong.setBackgroundResource(R.drawable.button_quanxian);
            holder.openZiqidong.setTextColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.close_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_close) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    public static boolean isHasAndroidAuto(SuperActivity activity) {
        try {
            PackageInfo packageInfo = activity.getPackageManager().getPackageInfo("com.google.android.projection.gearhead", 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检查是否存在自启动权限
     */
    public static boolean isHaveSelfStarting(SuperActivity activity) {
        return activity.getSharedPreferences("permissions_status", 0).getBoolean("selfStarting", false);
    }

    /**
     * 判断是否存在悬浮窗运行权限
     *
     * @return true不存在
     */
    public static boolean isNotHaveSuspensionWindow(SuperActivity activity) {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(activity);
    }

    /**
     * 申请悬浮窗权限
     */
    public static void showSuspensionWindow(SuperActivity activity) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        activity.startActivityForResult(intent, 100);
    }

    /**
     * 判断是否存在允许后台运行权限
     */
    public static boolean isIgnoringBatteryOptimizations(SuperActivity activity) {
        if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)) {
            return true;
        }
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
        }
        return isIgnoring;
    }

    /**
     * 请求允许后台运行权限
     */
    public static void requestIgnoreBatteryOptimizations(Context context) {
        try {
            @SuppressLint("BatteryLife")
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void selfStartManagerSettingIntent(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName componentName = null;
        switch (getMobileType()) {
            case "Xiaomi":  // 红米Note4测试通过
                componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity");
                break;
            case "Letv":  // 乐视2测试通过
                intent.setAction("com.letv.android.permissionautoboot");
                break;
            case "samsung":  // 三星Note5测试通过
                componentName = ComponentName.unflattenFromString("com.samsung.android.sm/.app.dashboard.SmartManagerDashBoardActivity");
                break;
            case "HUAWEI":  // 华为测试通过
                componentName = ComponentName.unflattenFromString("com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity");//跳自启动管理
                break;
            case "vivo":  // VIVO测试通过
                componentName = ComponentName.unflattenFromString("com.iqoo.secure/.safeguard.PurviewTabActivity");
                break;
            case "Meizu":  //万恶的魅族
                componentName = ComponentName.unflattenFromString("com.meizu.safe/.permission.SmartBGActivity");//跳转到后台管理页面
                break;
            case "OPPO":  // OPPO R8205测试通过
                componentName = ComponentName.unflattenFromString("com.oppo.safe/.permission.startup.StartupAppListActivity");
                break;
            case "ulong":  // 360手机 未测试
                componentName = new ComponentName("com.yulong.android.coolsafe", ".ui.activity.autorun.AutoRunListActivity");
                break;
        }
        if (componentName == null) {
            intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        } else {
            intent.setComponent(componentName);
            try {
                context.startActivity(intent);
            } catch (Exception e) {//抛出异常就直接打开设置页面
                intent = new Intent(Settings.ACTION_SETTINGS);
                context.startActivity(intent);
            }
        }
    }

    //获取手机类型
    private static String getMobileType() {
        return Build.MANUFACTURER;
    }

}
